<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useIndexStore } from '../../pinia'
import { ElMessage } from 'element-plus'
import { request } from '@/utils/axios/request.js'
import local from '@/components/local.vue'

let locabob = ref(false)

let state = useIndexStore()
let nickname = ref('')
let katable = ref("新增")
let status2 = ref('')
let newid = ref('')
let input = reactive({
    "nickname": "",
    "type": "",
    "content": "",
    "status": "",
    "creator": "",
    "createdTime": ""
})
let delCai = () => {
    katable.value = "新增"
    caiDanS.value = false
    input = reactive({
        "nickname": "",
        "type": "",
        "content": "",
        "status": "",
        "creator": "",
        "createdTime": ""
    })
}
//弹框显示隐藏
let caiDanS = ref(false)
let option1 = reactive([
    {
        value: '消息',
        label: '消息',
    },
    {
        value: '公告',
        label: '公告',
    },
])
let option2 = reactive([
    {
        value2: '正常',
        labe2: '正常',
    },
    {
        value2: '停用',
        labe2: '停用',
    },
])
let tableData = ref([])
//请求数据
onMounted(async () => {
    try {
        locabob.value = true
        let resData = await request({
            url: '/admin/message/messageSearch',
            method: 'get',
        })
        tableData.value = resData.data.sort((a, b) => b.id - a.id)
    } catch (err) {
        console.log(err);
    }
    locabob.value = false
})
let SearchAll = async () => {
    try {
        locabob.value = true
        let resData = await request({
            url: '/admin/message/messageSearch',
            method: 'get',
        })
        tableData.value = resData.data.sort((a, b) => b.id - a.id)
    } catch (err) {
        console.log(err);
    }
    locabob.value = false
}
//新增
let newinput = reactive({})
let add = () => {
    caiDanS.value = true
    input.createdTime = new Date().toLocaleString()
}
//修改

let update = (data) => {
    newid.value = data
    input.createdTime = new Date().toLocaleString()
    katable.value = "修改"
    caiDanS.value = true
    tableData.value.forEach((item, index) => {
        if (item.id == data) {
            input.nickname = item.nickname
            input.type = item.type
            input.content = item.content
            input.status = item.status
            input.creator = item.creator
        }
    })
}
//删除
let lastid = ref('')
let current = ref({
    "nickname": "",
    "type": "",
    "content": "",
    "status": "",
    "creator": "",
    "createdTime": ""
})
let del = async (id) => {
    lastid.value = id
    tableData.value.forEach((item, index) => {
        if (item.id == id) {
            current.value.nickname = item.nickname
            current.value.type = item.type
            current.value.content = item.content
            current.value.status = item.status
            current.value.creator = item.creator
            current.value.createdTime = item.createdTime
        }
    })
}
//取消删除
const cancelEvent = () => {
    console.log('cancel!')
}
//确认删除
const confirmEvent = async () => {
    try {
        locabob.value = true
        let data = await request({
            url: '/admin/message/messagedel',
            method: 'delete',
            data: { id: lastid.value }
        })
        tableData.value.forEach((item, index) => {
            if (item.id == lastid.value) {
                tableData.value.splice(index, 1)
            }
        })
        ElMessage.success(data.message)
    } catch (err) {
        console.log(err);
    }
    try {
        let Recycledata = await request({
            url: '/admin/message/Recycleadd',
            method: 'post',
            data: current.value
        })
        Recycleall()
    } catch (error) {
        console.log(error);
    }
    locabob.value = false
}
//确认新增按钮
let save = async () => {
    input.createdTime = new Date().toLocaleString()
    if (katable.value == "新增") {
        input.creator = localStorage.getItem('username')
        newinput = JSON.parse(JSON.stringify(input))
        if (newinput.nickname == '' || newinput.type == '' || newinput.content == '' || newinput.status == '') {
            ElMessage.error('信息不能为空')
            return;
        }
        try {
            locabob.value = true
            newinput.createdTime = new Date().toLocaleString()
            let data = await request({
                url: '/admin/message/messageadd',
                method: 'post',
                data: newinput
            })
            ElMessage.success(data.message)
        } catch (err) {
            console.log(err);
        }
        locabob.value = false
    } else if (katable.value == "修改") {
        try {
            locabob.value = true
            let data = await request({
                url: '/admin/message/messageadd1',
                method: 'put',
                data: {
                    content: input.content,
                    createdTime: input.createdTime,
                    status: input.status,
                    type: input.type,
                    nickname: input.nickname,
                    id: newid.value
                }
            })
            let obj = JSON.parse(JSON.stringify(input))
            if (obj.nickname == '' || obj.type == '' || obj.content == '' || obj.status == '') {
                alert('不能为空')
                return;
            }
            tableData.value.forEach((item, index) => {
                if (item.id == newid.value) {
                    tableData.value[index].nickname = input.nickname
                    tableData.value[index].type = input.type
                    tableData.value[index].content = input.content
                    tableData.value[index].status = input.status
                    tableData.value[index].createdTime = input.createdTime
                }
            })
            ElMessage.success(data.message)
        } catch (err) {
            console.log(err);
        }
        locabob.value = false
    }
    SearchAll()
    delCai();
}
//重置
let closed = async () => {
    if (Recycletext.value == "关闭") {
        Recycleall();
        nickname.value = ''
        status2.value = ''
        return;
    }
    try {
        locabob.value = true
        let resData = await request({
            url: '/admin/message/messageSearch',
            method: 'get',
        })
        tableData.value = resData.data
        nickname.value = ''
        status2.value = ''
        ElMessage.success("重置成功")
    } catch (err) {
        console.log(err);
    }
    locabob.value = false
}

// 模糊查询
const search = async () => {
    if (Recycletext.value == "关闭") {
        try {
            locabob.value = true
            let newdata = await request({
                url: `/admin/message/Recycles?nickname=${nickname.value}&status=${status2.value}`,
                method: 'get'
            })
            // 显示成功信息
            ElMessage.success("查询成功")
            newRecycledata.value = newdata.data
        } catch (err) {
            console.log(err);
        }
        locabob.value = false
        return;
    }
    try {
        locabob.value = true
        let newdata = await request({
            url: `/admin/message/messages?nickname=${nickname.value}&status=${status2.value}`,
            method: 'get'
        })
        // 显示成功信息
        ElMessage.success("查询成功")
        tableData.value = newdata.data
    } catch (err) {
        console.log(err);
    }
    locabob.value = false
}

let currentPage = ref(1);
let pageSize = ref(10);
let currentDate = computed(() => {
    let statIndex = (currentPage.value - 1) * pageSize.value
    let endIndex = currentPage.value * pageSize.value
    return tableData.value.slice(statIndex, endIndex);
})

// 文件导出
import * as XLSX from 'xlsx'
const fileOut = () => {
    if (confirm('确认导出吗')) {
        const data = tableData.value; // json数据
        const sheetName = 'message'; // 表格名称
        const sheetHeader = ["nickname", "type", "content", "status", "creator", "createdTime"]; // 表头
        const sheetData = data.map(item => [item.nickname, item.type, item.content, item.status, item.creator, item.createdTime]); // 表格数据
        sheetData.unshift(sheetHeader); // 将表头插入表格数据第一行
        const worksheet = XLSX.utils.aoa_to_sheet(sheetData); // 将表格数据转换为worksheet
        const workbook = XLSX.utils.book_new(); // 创建workbook
        XLSX.utils.book_append_sheet(workbook, worksheet, sheetName); // 将worksheet插入workbook
        XLSX.writeFile(workbook, 'message.xlsx'); // 下载表格
    }
}

// 文件导入
const fileOver = (event) => {
    const file = event.target.files[0]; // 获取上传的文件
    const reader = new FileReader(); // 创建FileReader对象
    reader.onload = async (e) => {
        const data = e.target.result; // 获取文件内容
        const workbook = XLSX.read(data, { type: 'binary' }); // 将文件内容转换为workbook
        const worksheet = workbook.Sheets[workbook.SheetNames[0]]; // 获取第一个worksheet
        const sheetData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // 将worksheet转换为json数据
        const header = sheetData[0]; // 获取表头
        const jsonData = sheetData.slice(1).map(row => {
            const obj = {};
            header.forEach((h, i) => {
                obj[h] = row[i];
            });
            return obj;
        }); // 将表格数据转换为json数据
        try {
            locabob.value = true
            let data = await request({
                url: '/admin/message/messageadd1',
                method: 'post',
                data: jsonData
            })
            SearchAll()
            ElMessage.success(data.message)
        } catch (err) {
            console.log(err);
        }
        locabob.value = false
    };
    reader.readAsBinaryString(file); // 读取文件内容
}
//=======================================回收站===========================================
// 小眼睛
let showPassword = ref(false)
//确认密码弹窗
let dialogFormVisible = ref(false)
let form = reactive({
    password1: '',
    password2: '',
})
let newRecycledata = ref([])
//封装查询所有数据
let Recycleall = async () => {
    try {
        let Recycledata = await request({
            url: "/admin/message/RecycleAll",
            method: 'get'
        })
        newRecycledata.value = Recycledata.data.sort((a, b) => b.id - a.id)
    } catch (err) {
        console.log(err);
    }
}
let boxShow = ref(true)
let Recycletext = ref("回收站")
//回收按钮
let Recycle = () => {
    if (Recycletext.value == "回收站") {
        boxShow.value = false
        Recycleall()
        Recycletext.value = "关闭"
        nickname.value = ''
        status2.value = ''
    } else if (Recycletext.value == "关闭") {
        boxShow.value = true
        Recycletext.value = "回收站"
        nickname.value = ''
        status2.value = ''
    }
}
//回收站删除按钮
let Recycleid = ref('')
let remove = (id) => {
    dialogFormVisible.value = true
    Recycleid.value = id
}

//确认密码删除
let passave = async () => {
    let userItems = ref('')
    let usernameLoca = localStorage.getItem('username')
    if (usernameLoca) {
        try {
            let newdata = await request({
                url: `/admin/user/users1?username=${usernameLoca}`,
                method: 'get'
            })
            userItems.value = newdata.data[0]
        } catch (err) {
            console.log(err);
        }
    }
    if (form.password1 != userItems.value.password) {
        ElMessage.error('原始密码错误')
        form.password1 = ''
        form.password2 = ''
        return;
    } else if (form.password2 != userItems.value.password) {
        ElMessage.error('确认密码错误')
        form.password2 = ''
        return;
    } else if (form.password2 == userItems.value.password || userItems.value.password == form.password1) {
        try {
            locabob.value = true
            let data = await request({
                url: '/admin/message/Recycledel',
                method: 'delete',
                data: { id: Recycleid.value }
            })
            Recycleall()
            ElMessage.success(data.message)
            dialogFormVisible.value = false
            form.password1 = ''
            form.password2 = ''

        } catch (err) {
            console.log(err);
        }
        locabob.value = false
    }
}

//恢复按钮
let recover = (id) => {
    Recycleid.value = id
    newRecycledata.value.forEach((item, index) => {
        if (item.id == id) {
            current.value.nickname = item.nickname
            current.value.type = item.type
            current.value.content = item.content
            current.value.status = item.status
            current.value.creator = item.creator
            current.value.createdTime = item.createdTime
        }
    })
}
//恢复确认弹窗
let confirmrecover = async () => {
    try {
        locabob.value = true
        let data = await request({
            url: '/admin/message/Recycledels',
            method: 'delete',
            data: { id: Recycleid.value }
        })
        Recycleall()
        ElMessage.success(data.message)
    } catch (err) {
        console.log(err);
    }
    try {
        let Recycledata = await request({
            url: '/admin/message/messageadd',
            method: 'post',
            data: current.value
        })
        SearchAll()
    } catch (error) {
        console.log(error);
    }
    locabob.value = false
}
</script>

<template>
    <div class="nav">
        <local v-show="locabob" />
        <ul class="nav_ul">
            <li>
                标题:&nbsp;
            </li>
            <li>
                <el-input v-model="nickname" placeholder="请输入标题" />
            </li>
            <li>状态:&nbsp;
                <el-select v-model="status2" class="m-2" placeholder="请选择角色状态" size="large">
                    <el-option v-for="item in option2" :key="item.value2" :label="item.labe2" :value="item.value2" />
                </el-select>
            </li>
            <li><el-button type="primary" @click="search">搜索</el-button></li>
            <li><el-button @click="closed">重置</el-button></li>
            <li style="margin-left: 10px;" v-show="boxShow"><el-button type="primary" @click="add"
                    v-show="state.role == 0 || state.role == 1">新增</el-button></li>
            <li><el-button type="success" @click="fileOut">文件导出</el-button></li>
            <li v-show="state.role == 1 || state.role == 0">
                <label for="files">
                    <p class="daoRu">文件导入</p>
                </label>
                <input type="file" style="display: none;" id="files" @change="fileOver">
            </li>
            <li style="margin-left: 10px;"><el-button type="primary" @click="Recycle" v-show="state.role == 0">{{
                Recycletext }}</el-button></li>
        </ul>
        <div class="type_ul" v-show="boxShow">
            <el-table ref="multipleTableRef" :data="currentDate">
                <el-table-column fixed prop="nickname" label="标题" show-overflow-tooltip />
                <el-table-column property="type" label="类型" />
                <el-table-column property="content" label="内容" show-overflow-tooltip />
                <el-table-column property="status" label="状态" />
                <el-table-column property="creator" label="创建者" />
                <el-table-column property="createdTime" label="创建时间" show-overflow-tooltip />
                <el-table-column fixed="right" label="操作" v-if="state.role == 0 || state.role == 1">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click.prevent="update(scope.row.id)"
                            v-show="state.role == 0 || state.role == 1">
                            修改
                        </el-button>
                        <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="#626AEF" title="确定删除吗?"
                            @confirm="confirmEvent" @cancel="cancelEvent">
                            <template #reference>
                                <el-button link type="primary" size="small" @click.prevent="del(scope.row.id)"
                                    v-show="state.role == 0">
                                    删除
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 回收站表 -->
        <div class="type_ul" v-show="!boxShow">
            <el-table ref="multipleTableRef" :data="newRecycledata">
                <el-table-column fixed prop="nickname" label="标题" show-overflow-tooltip />
                <el-table-column property="type" label="类型" />
                <el-table-column property="content" label="内容" show-overflow-tooltip />
                <el-table-column property="status" label="状态" />
                <el-table-column property="creator" label="创建者" />
                <el-table-column property="createdTime" label="创建时间" show-overflow-tooltip />
                <el-table-column fixed="right" label="操作" v-if="state.role == 0 || state.role == 1">
                    <template #default="scope">
                        <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="#626AEF" title="确定恢复吗?"
                            @confirm="confirmrecover" @cancel="cancelEvent">
                            <template #reference>
                                <el-button link type="primary" size="small" @click.prevent="recover(scope.row.id)">
                                    恢复
                                </el-button>
                            </template>
                        </el-popconfirm>
                        <el-button link type="primary" size="small" @click.prevent="remove(scope.row.id)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class=" demo-pagination-block" v-show="boxShow">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
                layout="total, sizes, prev, pager, next, jumper" :total="tableData.length" />
        </div>
        <!-- 回收站分页 -->
        <div class=" demo-pagination-block" v-show="!boxShow">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
                layout="total, sizes, prev, pager, next, jumper" :total="newRecycledata.length" />
        </div>
        <div class="sheZhi" :style="{ width: caiDanS ? '460px' : '0' }">
            <dl>
                <dt>
                <dd>{{ katable }}</dd>
                <dd @click="delCai"><span class="iconfont icon-shanchu2"></span></dd>
                </dt>
            </dl>
            <ul>
                <li>
                    <span>{{ katable == "新增" ? '创建时间' : '修改时间' }}:&nbsp;</span>
                    <el-input v-model="input.createdTime" clearable disabled />
                </li>
                <li>
                    <span>标题:&nbsp;</span>
                    <el-input v-model="input.nickname" placeholder="请输入标题" clearable />
                </li>
                <li>
                    <span>类型:&nbsp;</span>
                    <el-select v-model="input.type" placeholder="请选择类型">
                        <el-option v-for=" item  in  option1 " :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </li>
                <li>
                    <span>内容:&nbsp;</span>
                    <el-input v-model="input.content" type="textarea" placeholder="请输入内容" />
                </li>
                <li>
                    <span>状态:&nbsp;</span>
                    <el-select v-model="input.status" placeholder="请选择状态">
                        <el-option v-for=" item  in  option2 " :key="item.value2" :label="item.labe2" :value="item.value2">
                        </el-option>
                    </el-select>
                </li>
                <li>
                    <el-button type="primary" @click="save">保存</el-button>
                    <el-button @click="delCai">取消</el-button>
                </li>
            </ul>
        </div>
        <div class="mengBan" v-show="caiDanS" @click="delCai"></div>
        <div class="popbox">
            <el-dialog v-model="dialogFormVisible" title="确认密码">
                <el-form :model="form">
                    <el-form-item label="原始密码" label-width="140px">
                        <el-input v-model="form.password1" type="password" autocomplete="off" :show-password="true" />
                        <i class="el-icon-view el-input__icon" slot="suffix" @click="showPassword = !showPassword"></i>
                    </el-form-item>
                    <el-form-item label="确认密码" label-width="140px">
                        <el-input v-model="form.password2" type="password" autocomplete="off" :show-password="true" />
                        <i class="el-icon-view el-input__icon" slot="suffix" @click="showPassword = !showPassword"></i>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="passave">
                            确认删除
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<style scoped lang="less">
.daoRu {
    width: 80px;
    height: 32px;
    color: white;
    border-radius: 5px;
    background-color: #7ec050;
    text-align: center;
    line-height: 32px;
    font-weight: 400;
    margin-top: 10px;
}

.nav {
    background-color: #fafafa;
    display: flex;
    flex-direction: column;
    height: calc(100% - 85px);

    .nav_ul {
        display: flex;
        flex-shrink: 0;
        height: 50px;
        line-height: 50px;
        font-size: 14px;
        padding-left: 20px;
        margin-top: 10px;

        li {
            font-weight: 700;
            margin-left: 10px;
        }

        ;
    }

    .type_ul {
        display: flex;
        padding: 0 20px;
    }

    .demo-pagination-block {
        padding-bottom: 40px;
        overflow: hidden;
        align-self: center;
    }

    .sheZhi {
        width: 0px;
        height: 100%;
        position: fixed;
        top: 0;
        right: 0;
        background-color: white;
        z-index: 1001;
        box-shadow: -1px 0 10px rgb(143, 143, 143);
        transition: all 0.3s ease-in-out;

        dl {
            display: flex;
            flex-direction: column;

            dt:nth-child(1) {
                width: 100%;
                padding: 16px 24px;
                display: flex;
                justify-content: space-between;
                border-bottom: 0.5px solid rgba(216, 214, 214, 0.5);
                margin-bottom: 45px;


                dd:nth-child(1) {
                    font-size: 20px;
                }

                dd:nth-child(2) {
                    margin-right: 60px;

                }
            }

        }

        ul {
            display: flex;
            flex-direction: column;
            padding: 0 30px;

            .demo-pagination-block {
                padding-bottom: 40px;
                overflow: hidden;
                align-self: center;
            }

            li {
                margin-bottom: 20px;
                display: flex;
                align-items: center;

                span {
                    flex-shrink: 0;
                    margin-right: 20px;
                    font-weight: 600;
                    font-size: 14px;
                }
            }
        }
    }

    // 蒙版
    .mengBan {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1000;
        background-color: rgba(247, 247, 247, 0.3);
        filter: brightness(1%);
    }
}

.popbox {

    :deep .el-input {
        width: 300px;
    }

    .dialog-footer button:first-child {
        margin-right: 10px;
    }

    :deep .el-form {
        margin-left: 50px;
    }
}
</style>